<?php
declare (strict_types=1);

namespace app\admin\service\base;

use app\admin\model\base\OfficialAccountMenu;
use app\admin\model\base\OfficialAccountMessages;
use app\admin\validates\OfficialAccountMessagesValidate;
use app\admin\validates\OfficialAccountValidate;
use app\BaseService;
use think\exception\ValidateException;
use think\response\Json;
use wechat\WsOfficialAccount;

/**
 * 公众号配置服务层
 */
class OfficialAccountService extends BaseService
{

    /**
     * 创建公众号菜单
     * @param array $params
     * @return Json
     */
    public function createWxMenu(array $params): Json
    {
        //数据验证
        try {
            validate(OfficialAccountValidate::class)->scene('add')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        if ($params['pid'] > 0) {
            //验证子菜单是否超过五个
            if (OfficialAccountMenu::where('pid', '=', $params['pid'])->count() >= 5) return jsonReturn(0, [], '菜单已经超过5个');
        } else {
            if (OfficialAccountMenu::where('pid', '=', 0)->count() >= 3) return jsonReturn(0, [], '菜单已经超过3个');
        }
        //生成指定的key
        if ($params['type'] == 'click') $params['key'] = rand(100, 999) . '_MENU_' . date('YmdHis');
        //保存数据
        $res = OfficialAccountMenu::create([
            'name' => $params['name'],
            'type' => $params['type'],
            'pid' => $params['pid'] ?? 0,
            'sort' => $params['sort'],
            'url' => $params['url'] ?? '',
            'key' => $params['key'] ?? '',
            'content' => $params['content'] ?? '',
            'messages_type' => $params['messages_type'],
            'media_id' => $params['media_id'] ?? '',
            'path' => $params['path'] ?? '',
        ]);
        if (!$res) return jsonReturn(0, [], '创建失败');
        return jsonReturn(1, [], '创建成功');
    }

    /**
     * 创建公众号菜单
     * @param array $params
     * @return Json
     */
    public function updateWxMenu(array $params): Json
    {
        //数据验证
        try {
            validate(OfficialAccountValidate::class)->scene('update')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        $info = OfficialAccountMenu::where('id', '=', $params['id'])->find();

        if(!$info) return jsonReturn(0, [], '数据不存在');

        $pid = $params['pid'] ?? 0;
        //验证菜单是否超过
        if ($info->pid != $pid) {
            //验证子菜单是否超过五个
            if ($pid > 0) {
                //验证子菜单是否超过五个
                if (OfficialAccountMenu::where('pid', '=', $pid)->count() >= 5) return jsonReturn(0, [], '菜单已经超过5个');
            } else {
                if (OfficialAccountMenu::where('pid', '=', 0)->count() >= 3) return jsonReturn(0, [], '菜单已经超过3个');
            }
        }
        //保存数据
        $res = OfficialAccountMenu::where('id', '=', $params['id'])->update([
            'name' => $params['name'],
            'type' => $params['type'],
            'pid' => $pid,
            'sort' => $params['sort'],
            'url' => $params['url'] ?? '',
            'key' => $params['key'] ?? '',
            'content' => $params['content'] ?? '',
            'messages_type' => $params['messages_type'],
            'media_id' => $params['media_id'] ?? '',
            'path' => $params['path'] ?? '',
        ]);
        if (!$res) return jsonReturn(0, [], '更新失败');
        return jsonReturn(1, [], '更新成功');
    }

    /**
     * 发布微信公众号菜单
     * @return Json
     */
    public function pushWxMenu(): Json
    {
        //组装微信菜单创建格式
        $list = OfficialAccountMenu::getWxMenu();
        if ($list) {
            $wx = new WsOfficialAccount();
            return jsonReturn(1, $wx->createMenu($list));
        }
        return jsonReturn(0, [], '菜单不能为空');
    }

    /**
     * 删除公众号菜单
     * @param array $params
     * @return Json
     */
    public function deleteWxMenu(array $params): Json
    {
        //数据验证
        try {
            validate(OfficialAccountValidate::class)->scene('delete')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }

        $info = OfficialAccountMenu::where('id', '=', $params['id'])->find();
        if(!$info) return jsonReturn(0, [], '数据不存在');
        if ($info->pid == 0) {
            if (OfficialAccountMenu::where('pid', '=', $info->id)->count() > 0) {
                return jsonReturn(0, [], '请先删除子菜单');
            }
        }
        //保存数据
        $res = OfficialAccountMenu::where('id', '=', $params['id'])->delete();
        if (!$res) return jsonReturn(0, [], '删除失败');
        return jsonReturn(1, [], '删除成功');
    }

    /**
     * 创建公众号菜单
     * @return Json
     */
    public function getWxMenuList(): Json
    {
        return jsonReturn(1, OfficialAccountMenu::getMenu());
    }

    /**
     * 获取当前公众号配置
     * @return Json
     */
    public function getMenuCurrent(): Json
    {
        $wx = new WsOfficialAccount();
        return jsonReturn(1, $wx->getMenuCurrent());
    }

    /**
     * 验证公众号
     * @return Json
     */
    public function token(): Json
    {
        $wx = new WsOfficialAccount();
        return jsonReturn(1, $wx->wechatOfficialAccount());
    }

    /**
     * 查询已设置的菜单
     * @return Json
     */
    public function getMenuList(): Json
    {
        $wx = new WsOfficialAccount();
        $wxList = $wx->getMenuList();
        if (!isset($wxList['menu']['button'])) return jsonReturn(0, [], '未设置菜单或没权限');
        if (empty($wxList['menu']['button'])) return jsonReturn(0, [], '菜单为空');
        //删除所有菜单，组装所有菜单格式
        OfficialAccountMenu::where('id', '>', 0)->delete();
        $button = $wxList['menu']['button'];
        foreach ($button as $k => $item) {
            $addData = ['name' => $item['name']];
            $addData['pid'] = 0;
            $addData['sort'] = $k;
            if (empty($item['sub_button'])) {
                $addData['type'] = $item['type'] ?? '';
                $addData['url'] = $item['url'] ?? '';
                $addData['key'] = $item['key'] ?? '';
            }
            $addInfo = OfficialAccountMenu::create($addData);
            if (!empty($item['sub_button'])) {
                foreach ($item['sub_button'] as $kk => $value) {
                    OfficialAccountMenu::create([
                        'pid' => $addInfo->id,
                        'name' => $value['name'],
                        'type' => $value['type'] ?? '',
                        'url' => $value['url'] ?? '',
                        'key' => $value['key'] ?? '',
                        'sort' => $kk,
                    ]);
                }
            }
        }
        return jsonReturn(1, []);
    }

    /**
     * 菜单
     * @param array $menu
     * @return Json
     */
    public function createMenu(array $menu): Json
    {
        $wx = new WsOfficialAccount();
        return jsonReturn(1, $wx->createMenu($menu));
    }

    /**
     * 删除所有菜单
     * @return Json
     */
    public function deleteMenuAll(): Json
    {
        $wx = new WsOfficialAccount();
        $res = $wx->deleteMenuAll();
        if ($res['errcode'] != 0) return jsonReturn(0, [], '删除失败');
        //删除所有数据
        $res = OfficialAccountMenu::where('id', '>', 0)->delete();
        if (!$res) return jsonReturn(0, [], '删除失败');
        return jsonReturn(1, []);
    }

    /**
     * 删除指定菜单
     * @param int $meunId
     * @return Json
     */
    public function deleteMenuOne(int $meunId): Json
    {
        $wx = new WsOfficialAccount();
        return jsonReturn(1, $wx->deleteMenuOne($meunId));
    }

    /**
     * 获取自动回复设置
     * @return Json
     */
    public function autoRely(): Json
    {
        $wx = new WsOfficialAccount();

        return jsonReturn(1, $wx->getAutoRely());
    }

    /**
     * 获取关键字设置列表
     * @param array $where
     * @return Json
     */
    public function getKeywordList(array $where): Json
    {
        $list_rows = request()->param('page_size') ?? 10;
        $list = OfficialAccountMessages::where($where)->order('id', 'desc')->paginate([
            'list_rows' => intval($list_rows),
            'var_page' => 'page',
        ]);
        return jsonReturn(1, $list);
    }

    /**
     * 创建关键字回复
     * @param array $params
     * @return Json
     */
    public function createKeyword(array $params): Json
    {
        if (!isset($params['type'])) return jsonReturn(0, [], '参数错误');
        if ($params['type'] == '1') {
            $scene = 'add_g';
        } elseif ($params['type'] == '2') {
            $scene = 'add_gz';
        } elseif ($params['type'] == '3') {
            $scene = 'add_zd';
        } else {
            return jsonReturn(0, [], '参数错误');
        }
        //数据验证
        try {
            validate(OfficialAccountMessagesValidate::class)->scene($scene)->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        if (in_array($params['type'], [2, 3])) {
            if (OfficialAccountMessages::where('type', '=', $params['type'])->count()) return jsonReturn(0, [], '该消息只能创建一条');
        }
        $res = OfficialAccountMessages::create([
            'type' => $params['type'] ?? '',
            'content' => $params['content'] ?? '',
            'name' => $params['name'] ?? '',
            'key' => $params['key'] ?? '',
            'key_type' => $params['key_type'] ?? '1',
            'messages_type' => $params['messages_type'] ?? '',
            'media_id' => $params['media_id'] ?? '',
            'path' => $params['path'] ?? '',
        ], ['type', 'content', 'name', 'key', 'key_type', 'messages_type', 'media_id']);
        if (!$res) return jsonReturn(0, [], '创建失败');
        return jsonReturn(1, [], '创建成功');
    }

    /**
     * 更新关键词回复
     * @param array $params
     * @return Json
     */
    public function updateKeyword(array $params): Json
    {
        if (!isset($params['type'])) return jsonReturn(0, [], '参数错误');
        if ($params['type'] == '1') {
            $scene = 'update_g';
        } elseif ($params['type'] == '2') {
            $scene = 'update_gz';
        } elseif ($params['type'] == '3') {
            $scene = 'update_zd';
        } else {
            return jsonReturn(0, [], '参数错误');
        }
        //数据验证
        try {
            validate(OfficialAccountMessagesValidate::class)->scene($scene)->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        $id = $params['id'];
        $info = OfficialAccountMessages::find($id);
        $res = $info->allowField(['type', 'content', 'name', 'key', 'key_type', 'messages_type', 'media_id'])
            ->save([
                'type' => $params['type'] ?? '',
                'content' => $params['content'] ?? '',
                'name' => $params['name'] ?? '',
                'key' => $params['key'] ?? '',
                'key_type' => $params['key_type'] ?? '1',
                'messages_type' => $params['messages_type'] ?? '',
                'media_id' => $params['media_id'] ?? '',
                'path' => $params['path'] ?? '',
            ]);
        if (!$res) return jsonReturn(0, [], '编辑失败');
        return jsonReturn(1, [], '编辑成功');
    }

    /**
     * 删除关键字回复
     * @param array $params
     * @return Json
     */
    public function deleteKeyword(array $params): Json
    {
        //数据验证
        try {
            validate(OfficialAccountMessagesValidate::class)->scene('delete')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        $res = OfficialAccountMessages::where('id', '=', $params['id'])->where('type', '=', $params['type'])->delete();
        if (!$res) return jsonReturn(0, [], '删除失败');
        return jsonReturn(1, [], '删除成功');
    }
}
